//
//  LJNetworkTool.swift
//  LJWeibo
//
//  Created by Raymond on 15/12/17.
//  Copyright © 2015年 liu. All rights reserved.
//

import UIKit
import AFNetworking

enum LJNetworkError: Int{
    case emptyAccessToken = -1
    case emptyUid = -2
    
    var errorDescprition: String{
        get{
            switch self{
            case LJNetworkError.emptyAccessToken:
                return "access_token没有值"
            case LJNetworkError.emptyUid:
                return "uid没有值"
            }
        }
    }
    
    func error() -> NSError{
        return NSError(domain: "cn.lj.error.network", code: self.rawValue, userInfo: ["errorDescprtion" : self.errorDescprition])
    }
}

class LJNetworkTool: AFHTTPSessionManager {
    /// 返回单例
    static let shareInstance = LJNetworkTool()
    
    private  init() {
        let baseURL = NSURL(string: "https://api.weibo.com/")
        
        super.init(baseURL: baseURL, sessionConfiguration: nil)
        
        self.responseSerializer.acceptableContentTypes?.insert("text/plain")
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    let client_id = "2844924101"
    
    let client_secret = "adc2c4268fd1ad2eb5a4efd3b485abe3"
    
    let redirect_uri = "https://www.baidu.com"
    
    func aOuthURL() -> NSURL{
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        
        return NSURL(string: urlString)!
        
    }
    
    // 获取用户昵称和头像的方法
    func loadUserInfo( finished: (result: [String : AnyObject]?, error: NSError?) -> ()){
        guard let access_token = LJUserAccount.loadUserAccount()?.access_token else{
            let error = LJNetworkError.emptyAccessToken.error()
            finished(result: nil,error: error)
            return
        }
        
        guard let uid = LJUserAccount.loadUserAccount()?.uid else{
            let error = LJNetworkError.emptyUid.error()
            finished(result: nil,error: error)
            return
        }
        
        let urlString = "2/users/show.json"
        
        let parameters = [
            "access_token" : access_token,
            "uid" : uid
        ]
        
        GET(urlString, parameters: parameters, success: { (_, result) -> Void in
            let dict = result as? [String : AnyObject]
            finished(result: dict, error: nil)
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
        }
        
    }
    
    // 获取AccessToken的方法
    func loadAccessToken(code: String, finished: (result: [String : AnyObject]?, error: NSError?) -> ()){
        let urlString = "oauth2/access_token"
        
        // Oathur授权参数
        let parameters = [
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : redirect_uri
        ]
        
        POST(urlString, parameters: parameters, success: { (_, result) -> Void in
            // 强转
            let dict = result as? [String : AnyObject]
            // 回调
            finished(result: dict, error: nil)
            
            }) { (_, error) -> Void in
                
                finished(result: nil, error: error)
        }
        
    }
    
    
    
    // MARK: - 加载微博数据
    func loadStatus(since_id: Int, max_id: Int, finished: (result: [String : AnyObject]?, error: NSError?) -> ()){
        // 判断access_token是否有值
        guard let access_token = LJUserAccount.loadUserAccount()?.access_token else{
            let error = LJNetworkError.emptyAccessToken.error()
            finished(result: nil, error: error)
            return
        }
        
        // url
        let urlString = "2/statuses/home_timeline.json"
        
        // parameters
        var parameters: [String : AnyObject] = ["access_token" : access_token]
        
        if since_id > 0 {
            parameters["since_id"] = since_id
        }else if max_id > 0 {
            parameters["max_id"] = max_id - 1
        }
        
        // get
        GET(urlString, parameters: parameters, success: { (_, result) -> Void in
            let dict = result as? [String : AnyObject]
            finished(result: dict, error: nil)
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
        }
    }
    
    // MARK: - 发送微博
    func sendStatus(status: String, image: UIImage?, finished:(result: [String : AnyObject]?, error: NSError?) -> ()){
        // 判断有无access_token
        guard let access_token = LJUserAccount.loadUserAccount()?.access_token else {
            let error = LJNetworkError.emptyAccessToken.error()
            finished(result: nil, error: error)
            return
        }
        // url 
        let url = "2/statuses/update.json"
        
        // parameters
        let parameters = ["access_token": access_token, "status": status]
        
        // 判断有无图片
        if let img = image {
            sendImageStatus(parameters, status: status, image: img, finished: finished)
            
        } else {
            POST(url, parameters: parameters, success: { (_, result) -> Void in
                let dict = result as! [String : AnyObject]
                finished(result: dict, error: nil)
                }) { (_, error) -> Void in
                    finished(result: nil, error: error)
            }
        }
    }
    
    /// 上传图片的方法
    private func sendImageStatus(parameters: [String: AnyObject],status: String, image: UIImage, finished:(result: [String : AnyObject]?, error: NSError?) -> ()) {
        
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        
        POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
            let imageData = UIImagePNGRepresentation(image)!
            formData.appendPartWithFileData(imageData, name: "pic", fileName: "", mimeType: "image/png")
            }, success: { (_, result) -> Void in
                let dict = result as? [String: AnyObject]
                finished(result: dict, error: nil)
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
        }
    }
    
    // MARK: - 加载本地数据
    func loadLocalStatus(finished: (result: [String : AnyObject]?, error: NSError?) -> ()){
        let path = NSBundle.mainBundle().pathForResource("statuses", ofType: "json")!
        let data = NSData(contentsOfFile: path)!
        do {
            let json = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))
            let dict = json as? [String : AnyObject]
            finished(result: dict, error: nil)
        } catch {
            let error = NSError(domain: "cn.lj.loadlocalstatus", code: -3, userInfo: ["errorDescription" : "加载本地数据出错"])
            finished(result: nil, error: error)
        }
    }
    
}
